﻿using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LockDemo
{
    public class RedisDistributedLock : IDistributedLock
    {
        private readonly ConnectionMultiplexer _redisConnection;
        private IDatabase _database;

        public RedisDistributedLock(ConnectionMultiplexer redisConnection)
        {
            _redisConnection = redisConnection;
            _database = _redisConnection.GetDatabase();
        }

        public Task<bool> TryAcquireLockAsync(string resourceKey, TimeSpan? lockDuration = null)
        {
            var isLockAcquired = _database.StringSetAsync(resourceKey, 1, lockDuration, When.NotExists);
            return isLockAcquired;
        }

        public Task ReleaseLockAsync(string resourceKey)
        {
            return _database.KeyDeleteAsync(resourceKey);
        }
    }
}
